/** biome-ignore-all lint/suspicious/noExplicitAny: off */
import React, { useCallback } from 'react';
import type { TypedKey } from '../context/types';
import { globalContext } from '../globalContext';
import { useListen } from './useListen';

export function useBatch() {
  const batchUpdate = useCallback(
    <T extends Array<[TypedKey<any>, any]>>(updates: T) => {
      globalContext.batch(() => {
        updates.forEach(([key, value]) => {
          globalContext.setData(key, value as never, false);
        });
      });
    },
    [],
  );

  return batchUpdate;
}

// 添加useWatch钩子，用于监听值变化但不触发重渲染
export function useWatch<T>(
  key: TypedKey<T>,
  callback: (newValue: T, oldValue: T) => void,
  condition?: (newValue: T, oldValue: T) => boolean,
) {
  // 使用useEffect来订阅和取消订阅
  React.useEffect(() => {
    let oldValue = globalContext.getData(key);

    const unsubscribe = globalContext.subscribe(key, (newValue) => {
      const shouldNotify = !condition || condition(newValue, oldValue);
      if (shouldNotify) {
        callback(newValue, oldValue);
        oldValue = newValue;
      }
    });

    return unsubscribe;
  }, [key, callback, condition]);
}

// 添加useDebounce钩子，用于防抖更新
export function useDebounce<T>(
  key: TypedKey<T>,
  delay: number = 300,
  equalityFn?: (a: T, b: T) => boolean,
) {
  const [value, _setValue] = useListen(key, equalityFn);
  const [debouncedValue, setDebouncedValue] = React.useState(value);

  React.useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => clearTimeout(timer);
  }, [value, delay]);

  return debouncedValue;
}
